package sealte.hvpms.servlet.vp;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;

import sealte.hvpms.dao.impl.PollDAOImpl;
import sealte.hvpms.dao.impl.PollOptionDAOImpl;
import sealte.hvpms.pojo.PollOption;
import sealte.hvpms.pojo.UserCreate;
import sealte.hvpms.util.HVPMSTools;

public class GetVPsPieChart extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserCreate uc = (UserCreate)request.getSession().getAttribute("UserCreate");
		if(uc!=null){
			String id_str = request.getParameter("id");
			if(id_str!=null&&!id_str.equals("")&&HVPMSTools.isNum(id_str)){
				response.setCharacterEncoding("UTF-8"); 
				response.setContentType("image/jpeg");
				int id = Integer.parseInt(id_str); 
				DefaultPieDataset data = getDataSet(id);
				JFreeChart chart = ChartFactory.createPieChart3D((new PollDAOImpl()).getNameByID(id), data,true,false,false);
				PiePlot3D plot = (PiePlot3D)chart.getPlot();
				plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})",NumberFormat.getNumberInstance(),new DecimalFormat("0.00%")));
				plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
				ChartUtilities.writeChartAsJPEG(response.getOutputStream(), 1.0f, chart, 700,400,null);
			}else{
				response.setCharacterEncoding("UTF-8"); 
				response.setContentType("text/html");
				response.getWriter().println("系统出错了。。。");
			}
		}else{
			response.setCharacterEncoding("UTF-8"); 
			response.setContentType("text/html");
			response.getWriter().println("谢绝跨路径访问");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	private static DefaultPieDataset getDataSet(int id){
		Iterator<PollOption> iter = (new PollOptionDAOImpl()).getPOAll(id).iterator();
		DefaultPieDataset dataset = new DefaultPieDataset();
		PollOption po = null;
		while(iter.hasNext()){
			po = iter.next();
			dataset.setValue(po.getContent(), po.getCounter());
		}
		return dataset;
	}

}
